package com.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bbs.pojo.Comment;
import com.bbs.pojo.Context;
import com.bbs.properties.MyUserDetails;
import com.bbs.service.ICommentService;
import com.bbs.service.IContextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@Slf4j
@RequestMapping("/user/post")
public class PostController {
    @Autowired
    private IContextService contextService;

    @Autowired
    private ICommentService commentService; // 新增评论服务注入

    @GetMapping("")
    public String post() {
        return "post"; // 返回发布新帖子的页面
    }
    @PostMapping("/add")
    public String addPost(@RequestParam String title, @RequestParam String context, Model model, Authentication authentication) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId(); // 安全获取 id
        Context newPost = new Context();
        newPost.setTitle(title);
        newPost.setContext(context);
        newPost.setUserId(Math.toIntExact(id)); //
        newPost.setCreateTime(LocalDateTime.now());
        newPost.setCommentCount(0); // 初始评论数为0
        contextService.save(newPost);
        return "redirect:/user/index/1"; // 发布成功后重定向到帖子列表第一页
    }
    // 修改方法：处理帖子详情页面跳转
    @GetMapping("/detail/{contextId}")
    public String getContextDetail(@PathVariable Long contextId, Model model) {
        Context context = contextService.getById(contextId);
        if (context == null) {
            return "redirect:/user/index/1"; // 如果帖子不存在，重定向到首页
        }
        // 获取该帖子的评论列表
        List<Comment> comments = commentService.list(new QueryWrapper<Comment>()
                .eq("context_id", contextId)
                .orderByDesc("create_time"));
        model.addAttribute("context", context);
        model.addAttribute("comments", comments); // 添加评论列表到模型
        return "context-detail"; // 返回帖子详情页面
    }
}
